package com.rc.controller;

import cn.hutool.core.io.IoUtil;

import com.rc.entity.web.Result;
import com.rc.service.GeneratorService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.util.zip.ZipOutputStream;

/**
 * 代码生成
 */
@RestController
@RequestMapping("/gen/generator")
@AllArgsConstructor
@Api(value = "代码生成接口",tags = "代码生成接口")
public class GeneratorController {
    private final GeneratorService generatorService;

    /**
     * 生成代码（zip压缩包）
     */
    @GetMapping("download")
    //方法参数说明，name参数名；value参数说明，备注；dataType参数类型；required 是否必传；defaultValue 默认值
    @ApiImplicitParam(name = "tableIds", value = "数据表Id")
    @ApiOperation(value = "下载代码", notes = "下载代码")
    public void download(String tableIds, HttpServletResponse response) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);

        // 生成代码
        for (String tableId : tableIds.split(",")) {
            generatorService.downloadCode(tableId, zip);
        }

        IoUtil.close(zip);

        // zip压缩包数据
        byte[] data = outputStream.toByteArray();

        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"maku.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");

        IoUtil.write(response.getOutputStream(), false, data);
    }

    /**
     * 生成代码（自定义目录）
     */
    @ResponseBody
    @PostMapping("code")
    @ApiImplicitParam(name = "tableIds", value = "数据表Id")
    @ApiOperation(value = "生成代码", notes = "生成代码")
    public Result code(@RequestBody String[] tableIds) throws Exception {
        // 生成代码
        for (String tableId : tableIds) {
            generatorService.generatorCode(tableId);
        }

        return Result.SUCCESS();
    }

}